package com.bincloud.vue.admin.web.util.jasypt.impl;

import com.bincloud.vue.admin.common.exception.BaseException;
import com.bincloud.vue.admin.common.exception.CodeMsg;
import com.bincloud.vue.admin.web.util.config.RsaConfig;
import com.bincloud.vue.admin.web.util.jasypt.JasyptService;
import com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricConfig;
import com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricStringEncryptor;
import com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description: 加解密实现
 * @Author: bincloud, mvpzhou
 * @Date: Create By bincloud, mvpzhou on 2022/2/22
 */
@Service
@Slf4j
public class JasyptServiceImpl implements JasyptService {

    private static final SimpleAsymmetricConfig ENCRYPT_CONFIG;
    private static final SimpleAsymmetricConfig DECRYPT_CONFIG;

    static {
        ENCRYPT_CONFIG = new SimpleAsymmetricConfig();
        ENCRYPT_CONFIG.setKeyFormat(AsymmetricCryptography.KeyFormat.PEM);
        DECRYPT_CONFIG = new SimpleAsymmetricConfig();
        DECRYPT_CONFIG.setKeyFormat(AsymmetricCryptography.KeyFormat.PEM);
    }

    @Resource
    private RsaConfig rsaConfig;

    /**
     * 解密字符串
     *
     * @param word 字符串 密文
     * @return 解密字符串 明文
     */
    @Override
    public String decrypt(String word) {
        try {
            DECRYPT_CONFIG.setPrivateKey(rsaConfig.getPrivateKey());
            StringEncryptor encryptor = new SimpleAsymmetricStringEncryptor(DECRYPT_CONFIG);
            return encryptor.decrypt(word);
        } catch (Exception e) {
            throw new BaseException(CodeMsg.DECRYPT_FAIL);
        }
    }

    /**
     * 加密字符串
     *
     * @param word 字符串 明文
     * @return 加密字符串 密文
     */
    @Override
    public String encrypt(String word) {
        try {
            ENCRYPT_CONFIG.setPublicKey(rsaConfig.getPublicKey());
            StringEncryptor encryptor = new SimpleAsymmetricStringEncryptor(ENCRYPT_CONFIG);
            return encryptor.encrypt(word);
        } catch (Exception e) {
            throw new BaseException(CodeMsg.ENCRYPT_FAIL);
        }
    }
}
